using System.Collections.Specialized;
using System.Diagnostics;
using Sharp.Infrastructure;
using Sharp.Infrastructure.Search;
using Sharp.WebBooter;
using System.Linq;
using System.Text;
using System.Web;

namespace Sharp.WebBooter
{
    public static class PagedResultExtension
    {
        [DebuggerStepThrough]
        public static ReturnedData ToReturnedData<T>(this PagedResult<T> res)
        {
            var data = new ReturnedData
            {
                Draw = int.Parse(System.Web.HttpContext.Current.Request.Params["draw"]),
                RecordsTotal = res.TotalRecords,
                RecordsFiltered = res.TotalRecords,
                Data = res.Data
            };
            return data;
        }
    }

    public static class DataTableParameterExtension
    {
        [DebuggerStepThrough]
        public static PagingFeature ToPagingFeature(this DataTableParameter res)
        {
            PagingFeature pf = new PagingFeature(UIEngine.DataTables);
            
            var request = System.Web.HttpContext.Current.Request;
            var nameValue = new NameValueCollection
            {
                request.Form,
                request.QueryString
            };
            if (nameValue.AllKeys.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (string key in nameValue.AllKeys)
                {
                    if (key.StartsWith("columns[")) continue;
                    sb.AppendFormat("{0}={1}&", key, nameValue.GetValues(key)[0]);
                }

                pf.RequestString = sb.Remove(sb.Length - 1, 1).ToString();
            }

 
            pf.PageSize = res.Length;
            pf.PageNo = (res.Start + res.Length) / res.Length;

            if (res.Order != null)
            {
                var order = res.Order.First();
                if (res.Columns[order.Column].Data == "function")
                {
                    pf.SimpleSort = "Id DESC";
                }
                else
                {
                    pf.SimpleSort = res.Columns[order.Column].Data + " " + order.Dir.ToUpper();
                }
            }
            else
            {
                pf.SimpleSort = "Id DESC";
            }

            return pf;
        }
    }
}